<template>
  <div class="system-notice">
    <div class="page-header">
      <div class="header-title">
        <h2>系统通知</h2>
        <span class="subtitle">管理系统通知和公告</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddNotice">发布通知</el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="通知标题">
          <el-input v-model="filterForm.title" placeholder="请输入通知标题" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="通知类型">
           <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
            <el-option label="普通" value="普通"></el-option>
            <el-option label="重要" value="重要"></el-option>
            <el-option label="紧急" value="紧急"></el-option>
          </el-select> -->
        <!-- </el-form-item>  -->
        <!-- <el-form-item label="发布时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 260px;">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-operations">
        <el-button-group>
          <!-- <el-button size="small" @click="handleBatchDelete">批量删除</el-button> -->
          <el-button size="small" @click="handleRefresh">刷新</el-button>
        </el-button-group>
      </div>
      
      <el-table
        :data="noticeList"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column prop="content" label="通知内容" min-width="200">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewNoticeDetail(scope.row)">{{ scope.row.content }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="150">
          <template slot-scope="scope">
            <div class="tag-group">
              <el-tag 
                v-for="(tag, index) in (scope.row.tags || '').split(',')" 
                :key="index" 
                :type="getTagType(tag)"
                size="small"
                v-if="tag">
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发布人" width="120">
          <template slot-scope="scope">
            <span>{{ getUserName(scope.row.publisher) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="查看次数" width="100">
          <template>
            <span>0</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewNoticeDetail(scope.row)">查看</el-button>
            <!-- <el-button type="text" size="small" @click="editNotice(scope.row)">编辑</el-button> -->
            <el-button type="text" size="small" class="danger-button" @click="deleteNotice(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 通知详情对话框 -->
    <el-dialog title="通知详情" :visible.sync="noticeDetailVisible" width="60%">
      <div v-if="currentNotice" class="notice-detail">
        <div class="notice-header">
          <h2>系统通知</h2>
          <div class="notice-meta">
            <span>发布人: {{ getUserName(currentNotice.createUser) }}</span>
            <span>发布时间: {{ formatDateTime(currentNotice.createTime) }}</span>
            <span>类型: 
              <el-tag 
                v-for="(tag, index) in (currentNotice.tags || '').split(',')" 
                :key="index" 
                :type="getTagType(tag)"
                size="small"
                v-if="tag">
                {{ tag }}
              </el-tag>
            </span>
          </div>
        </div>
        <div class="notice-content">
          <p v-html="currentNotice.content"></p>
        </div>
        <div class="notice-attachments" v-if="currentNotice.attachments && currentNotice.attachments.length > 0">
          <h3>附件</h3>
          <div class="attachment-list">
            <div v-for="(file, index) in currentNotice.attachments" :key="index" class="attachment-item">
              <i :class="getFileIcon(file.name)"></i>
              <span>{{ file.name }}</span>
              <el-button type="text" @click="downloadFile(file)">下载</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑通知对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="editDialogVisible" width="70%">
      <el-form :model="noticeForm" :rules="noticeRules" ref="noticeForm" label-width="100px">
        <el-form-item label="通知内容" prop="content">
          <el-input 
            type="textarea" 
            :rows="8" 
            v-model="noticeForm.content" 
            placeholder="请输入通知内容，支持基本HTML格式">
          </el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input 
            v-model="noticeForm.tags" 
            placeholder="请输入标签，多个标签用英文逗号分隔，例如：系统,招新,重要">
          </el-input>
          <div class="tag-preview" v-if="noticeForm.tags">
            <span>预览：</span>
            <el-tag 
              v-for="(tag, index) in noticeForm.tags.split(',')" 
              :key="index" 
              :type="getTagType(tag)" 
              size="small"
              v-if="tag.trim()">
              {{ tag.trim() }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="通知范围" prop="stat">
          <el-radio-group v-model="noticeForm.stat">
            <el-radio :label="1">仅用户可见</el-radio>
            <el-radio :label="2">用户和社联成员可见</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNotice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from "@/utils/http";

export default {
  name: 'SystemNotice',
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('user')),
      // 筛选表单
      filterForm: {
        title: '',
        type: '',
        dateRange: []
      },
      // 通知列表
      noticeList: [
        {
          id: 1,
          title: '关于2023年社团年审的通知',
          type: '重要',
          publisher: '管理员',
          createTime: '2023-06-01 10:00:00',
          viewCount: 156,
          content: '<p>各社团：</p><p>根据《大学生社团管理条例》的相关规定，现将2023年社团年审工作安排如下：</p><p>1. 年审时间：2023年6月10日至6月30日</p><p>2. 年审材料：社团工作总结、财务报表、活动记录、成员名单等</p><p>3. 年审方式：线上提交材料，线下答辩</p><p>请各社团按时完成年审工作，未按时参加年审的社团将被视为自动放弃社团资格。</p><p>特此通知。</p>',
          attachments: [
            { name: '社团年审表格.docx', url: '#' },
            { name: '年审工作流程.pdf', url: '#' }
          ]
        },
        {
          id: 2,
          title: '社团活动场地申请流程更新',
          type: '普通',
          publisher: '管理员',
          createTime: '2023-06-05 14:30:00',
          viewCount: 98,
          content: '<p>各社团：</p><p>为了更好地管理校内活动场地资源，提高场地使用效率，现对社团活动场地申请流程进行如下调整：</p><p>1. 场地申请需提前7天在系统内提交</p><p>2. 大型活动（参与人数超过100人）需提前15天申请</p><p>3. 新增线上场地预约功能，可实时查看场地使用情况</p><p>新的申请流程将从2023年7月1日起正式实施。</p><p>特此通知。</p>',
          attachments: []
        },
        {
          id: 3,
          title: '暑期社团活动安全注意事项',
          type: '紧急',
          publisher: '管理员',
          createTime: '2023-06-10 09:15:00',
          viewCount: 210,
          content: '<p>各社团：</p><p>暑期将至，为确保社团活动安全有序开展，现就暑期社团活动安全事项通知如下：</p><p>1. 严格控制野外活动，确需开展的必须制定详细安全预案</p><p>2. 水上活动必须有专业人员指导，并配备救生设备</p><p>3. 大型活动必须有校医院医护人员在场</p><p>4. 晚间活动结束后，必须组织学生安全返回宿舍</p><p>请各社团高度重视安全工作，确保活动安全有序进行。</p><p>特此通知。</p>',
          attachments: [
            { name: '暑期活动安全手册.pdf', url: '#' }
          ]
        }
      ],
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 3
      },
      loading: false,
      selectedNotices: [],
      
      // 通知详情
      noticeDetailVisible: false,
      currentNotice: null,
      
      // 编辑通知
      editDialogVisible: false,
      dialogTitle: '发布通知',
      noticeForm: {
        id: null,
        content: '',
        tags: '系统,',  // 默认带有系统标签
        stat: 2,       // 默认为2，用户和社联成员可见
        attachments: []
      },
      noticeRules: {
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请输入至少一个标签', trigger: 'blur' }
        ],
        stat: [
          { required: true, message: '请选择通知范围', trigger: 'change' }
        ]
      },
      fileList: [],
      userCache: {} // 用于缓存用户信息
    }
  },
  created() {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/admin/login')
    }
    
    this.fetchNoticeList();
  },
  methods: {
    // 获取通知列表
    fetchNoticeList() {
      this.loading = true;
      
      // 返回Promise以便链式调用
      return httpInstance.post('/api/notice/get/2')
        .then(res => {
          if (res.code === 200) {
            this.noticeList = res.data || [];
            console.log("通知列表:", this.noticeList);
            
            this.pagination.total = this.noticeList.length;
          } else {
            this.$message.error(res.msg || '获取通知列表失败');
          }
          return res; // 返回响应以便链式调用
        })
        .catch(err => {
          console.error('获取通知列表失败:', err);
          this.$message.error('获取通知列表失败，请稍后重试');
          throw err; // 重新抛出错误以便链式调用
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 添加筛选方法
    applyFilters() {
      // 首先获取完整的通知列表
      let filteredList = [...this.noticeList];
      
      // 根据筛选条件过滤
      if (this.filterForm.title && this.filterForm.title.trim() !== '') {
        // 根据内容过滤（因为通知可能没有title字段，而是使用content字段）
        filteredList = filteredList.filter(item => 
          item.content?.toLowerCase().includes(this.filterForm.title.toLowerCase())
        );
      }
      
      // 更新列表
      this.noticeList = filteredList;
      this.pagination.total = filteredList.length;
    },
    
    // 搜索
    handleFilter() {
      // 先获取完整列表，然后应用过滤
      this.fetchNoticeList().then(() => {
        this.applyFilters();
      });
    },
    
    // 重置表单
    resetForm() {
      this.filterForm = {
        title: '',
        type: '',
        dateRange: []
      };
      // 重置后获取完整列表
      this.fetchNoticeList();
    },
    
    // 刷新
    handleRefresh() {
      this.fetchNoticeList();
    },
    
    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedNotices = selection;
    },
    
    // 批量删除
    handleBatchDelete() {
      if (this.selectedNotices.length === 0) {
        this.$message.warning('请至少选择一条通知');
        return;
      }
      
      this.$confirm(`确定要删除选中的 ${this.selectedNotices.length} 条通知吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        const ids = this.selectedNotices.map(item => item.id);
        this.noticeList = this.noticeList.filter(item => !ids.includes(item.id));
        this.pagination.total -= this.selectedNotices.length;
        this.selectedNotices = [];
        this.$message.success('删除成功');
        
        // 实际API调用
        // httpInstance.post('/api/admin/notice/batchDelete', { ids })
        //   .then(response => {
        //     if (response && response.code === 200) {
        //       this.$message.success('删除成功');
        //       this.fetchNoticeList();
        //     } else {
        //       this.$message.error(response?.msg || '删除失败');
        //     }
        //   })
        //   .catch(error => {
        //     console.error('批量删除通知失败:', error);
        //     this.$message.error('删除失败，请稍后重试');
        //   });
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 查看通知详情
    viewNoticeDetail(notice) {
      this.currentNotice = notice;
      this.noticeDetailVisible = true;
    },
    
    // 添加通知
    handleAddNotice() {
      this.dialogTitle = '发布通知';
      this.noticeForm = {
        id: null,
        content: '',
        tags: '系统,',  // 默认带有系统标签
        stat: 2,       // 默认为2，用户和社联成员可见
        attachments: [],
        publisher: ''
      };
      this.fileList = [];
      this.editDialogVisible = true;
    },
    
    // 编辑通知
    editNotice(notice) {
      this.dialogTitle = '编辑通知';
      this.noticeForm = {
        id: notice.id,
        content: notice.content,
        tags: notice.tags || '系统,',
        stat: notice.stat || 2,
        attachments: notice.attachments || []
      };
      this.fileList = [];
      this.editDialogVisible = true;
    },
    
    // 删除通知
    deleteNotice(notice) {
      this.$confirm(`确定删除标题为"${notice.title || notice.content}"的通知吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 这里假设删除API存在，若没有可以修改
          const response = await httpInstance.post(`/api/notice/delete/${notice.id}`);
          
          if (response && response.code === 200) {
            this.$message.success('删除成功');
            this.fetchNoticeList();
          } else {
            this.$message.error(response?.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除通知失败:', error);
          this.$message.error('删除失败，请稍后重试');
        }
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 文件上传相关方法
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
    },
    
    // 下载文件
    downloadFile(file) {
      this.$message.success(`开始下载文件: ${file.name}`);
      // 实际项目中可以通过window.open或创建a标签下载
    },
    
    // 提交通知表单
    submitNotice() {
      this.$refs.noticeForm.validate(async valid => {
        if (valid) {
          try {
            // 构建发布通知的请求数据
            const noticeData = {
              content: this.noticeForm.content,
              tags: this.noticeForm.tags, // 直接使用表单中的tags
              stat: this.noticeForm.stat,  // 直接使用表单中的stat
              publisher: this.userInfo.nickname
            };
            
            const response = await httpInstance.post('/api/notice/push', noticeData);
            
            if (response && response.code === 200) {
              this.$message.success('通知发布成功');
              this.editDialogVisible = false;
              // 重新获取通知列表
              this.fetchNoticeList();
            } else {
              this.$message.error(response?.msg || '通知发布失败');
            }
          } catch (error) {
            console.error('发布通知失败:', error);
            this.$message.error('通知发布失败，请稍后重试');
          }
        } else {
          return false;
        }
      });
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchNoticeList();
    },
    
    // 当前页变化
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.fetchNoticeList();
    },
    
    // 根据通知类型返回不同的标签类型
    getTagType(tag) {
      if (!tag) return '';
      const trimmedTag = tag.trim();
      const typeMap = {
        '系统': '',
        '招新': 'success',
        '重要': 'warning',
        '紧急': 'danger',
        '活动': 'info'
      };
      return typeMap[trimmedTag] || '';
    },
    
    // 根据文件名获取图标
    getFileIcon(fileName) {
      const extension = fileName.split('.').pop().toLowerCase();
      const iconMap = {
        'pdf': 'el-icon-document',
        'doc': 'el-icon-document',
        'docx': 'el-icon-document',
        'xls': 'el-icon-document',
        'xlsx': 'el-icon-document',
        'ppt': 'el-icon-document',
        'pptx': 'el-icon-document',
        'jpg': 'el-icon-picture',
        'jpeg': 'el-icon-picture',
        'png': 'el-icon-picture',
        'gif': 'el-icon-picture',
        'zip': 'el-icon-folder',
        'rar': 'el-icon-folder'
      };
      return iconMap[extension] || 'el-icon-document';
    },
    
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 获取用户名
    getUserName(userId) {
      if (!userId) return '系统';
      
      // 如果缓存中已经有该用户，直接返回
      if (this.userCache[userId]) {
        return this.userCache[userId].nickname || this.userCache[userId].username || userId;
      }
      
      // 异步获取用户信息并缓存
      this.fetchUserInfo(userId);
      
      // 在获取到用户信息之前，先显示用户ID
      return userId;
    },
    
    // 获取用户信息的方法
    fetchUserInfo(userId) {
      // 避免重复请求
      if (this.userCache[userId] === 'loading') return;
      
      this.userCache[userId] = 'loading';
      
      httpInstance.get(`/api/user/info/${userId}`)
        .then(res => {
          if (res.code === 200 && res.data) {
            this.userCache[userId] = res.data;
            // 强制更新视图
            this.$forceUpdate();
          }
        })
        .catch(err => {
          console.error('获取用户信息失败:', err);
          this.userCache[userId] = { nickname: userId };
        });
    }
  }
}
</script>

<style scoped>
.system-notice {
  padding-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.danger-button {
  color: #F56C6C;
}

/* 通知详情样式 */
.notice-detail {
  padding: 0 20px;
}

.notice-header {
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.notice-header h2 {
  margin: 0 0 15px 0;
  font-size: 20px;
  color: #303133;
}

.notice-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
  color: #909399;
}

.notice-content {
  line-height: 1.8;
  color: #606266;
  margin-bottom: 30px;
}

.notice-attachments h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
}

.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  width: calc(50% - 8px);
}

.attachment-item i {
  font-size: 20px;
  margin-right: 10px;
  color: #909399;
}

.attachment-item span {
  flex: 1;
  color: #606266;
}

/* 确保对话框内容可滚动 */
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

/* 标签组样式 */
.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 6px; /* 标签之间的间距 */
}

.el-tag {
  margin-right: 0; /* 覆盖默认的margin */
}

.notice-meta .el-tag {
  margin-left: 4px;
  margin-bottom: 4px;
}

/* 添加标签预览样式 */
.tag-preview {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tag-preview .el-tag {
  margin-right: 5px;
}
</style>
